import React from 'react';
import { Link, withRouter } from 'react-router-dom'
import PropTypes from 'prop-types'
import { observer, inject } from 'mobx-react';
import User from '../../stores/user_store'

// 引入Nav
import Nav from './nav';
import './index.scss';

@inject((stores) => {
  const store = {
    user: stores.user,
  }
  return store
})
@observer
class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      keyword: '',
    }
    this.onSearch = this.onSearch.bind(this)
    this.logOut = this.logOut.bind(this)
    this.inputChange = this.inputChange.bind(this)
  }
  componentDidMount() {
  }
  onSearch(e) {
    const key = e.keyCode || e.which;
    if (e.type === 'keyup' && key !== 13) { return }
    const url = /search/ + encodeURIComponent(this.state.keyword);
    this.props.history.push(url);
  }
  logOut() {
    this.props.user.logout().then(() => {
      this.props.history.push('/');
    })
  }
  inputChange(e) {
    this.setState({
      keyword: e.target.value,
    })
  }
  render() {
    const userNickName = this.props.user.userInfo.user_display_name
    const { isLogined } = this.props.user
    return (
      <div id="header">
        <div className="header-top">
          <div className="header-shadow" />
          <div className="header-bg" />
        </div>
        <div className="header-container">
          <div className="w">
            <h1 className="web-title">React 个人博客</h1>
            <div className="search-item">
              <input className="search" type="text" placeholder="请输入关键字" onChange={this.inputChange} onKeyUp={this.onSearch} />
              <button className="search-btn" onClick={this.onSearch}>搜索</button>
            </div>
            <Nav />
            {isLogined ?
              <div className="user">
                <Link to="/user-center"><span className="nick-name">欢迎:{userNickName}</span><span>个人中心</span></Link>
                <a onClick={this.logOut}>退出</a>
              </div> :
              <div className="user">
                <span><Link to="/user/regist">注册</Link></span>
                <span><Link to="/user/login/">登录</Link></span>
              </div>
            }
          </div>
        </div>
      </div>
    )
  }
}
export default withRouter(Header);
Header.propTypes = {
  user: PropTypes.instanceOf(User),
  history: PropTypes.objectOf(Object),
}
